package com.itheima.app.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.FocusUser;
import com.itheima.domain.mongo.Video;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.FocusUserService;
import com.itheima.service.mongo.VideoService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class VideoManager {

    @DubboReference
    VideoService videoService;

    @DubboReference
    UserInfoService userInfoService;

    @Autowired
    FdfsWebServer fdfsWebServer;
    @Autowired
    FastFileStorageClient fastFileStorageClient;

    @DubboReference
    FocusUserService focusUserService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Cacheable(value = "tanhua_video",key = "#userId+'_'+#pageNum+'_'+#pageSize")
    public PageBeanVo findRecommendVideoByPage(Long userId, Integer pageNum, Integer pageSize) {
        //1.远程调用videoservice查询数据
        PageBeanVo pageBeanVo = videoService.findRecommendVideoByPage(userId, pageNum, pageSize);

        //2.获取分页数据中videoList,遍历集合,获取每个video,获取发布者id,获取发布者userInfo
        List<VideoVo> voList = new ArrayList<>();

        List<Video> items = (List<Video>) pageBeanVo.getItems();
        if (CollUtil.isNotEmpty(items)) {
            for (Video video : items) {
                //获取发布者id,获取发布者userInfo
                UserInfo userInfo = userInfoService.findByUserId(video.getUserId());

                //3.将每个video和userInfo封装videoVo,将每个vo放入voList中
                VideoVo vo = new VideoVo();

                //先封装userInfo,再封装video
                vo.setUserInfo(userInfo);
                vo.setVideo(video);

                //判断是否关注了
                if(stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.FOCUS_USER,userId,video.getUserId()))){
                    vo.setHasFocus(1);
                }

                voList.add(vo);
            }
        }

        //4.将voList设置给pageBeanVo且返回
        pageBeanVo.setItems(voList);
        return pageBeanVo;
    }

    //@CacheEvict(value = "tanhua_video",allEntries = true)//清除所有缓存
    @CacheEvict(value = "tanhua_video",key = "#userId+'_*'")//清除指定用户的key,需要导入笔记上自定义的三个类
    public void save(Long userId, MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //1.把封面存入fastDFS
        StorePath storePath1 = fastFileStorageClient.uploadFile(videoThumbnail.getInputStream(), videoThumbnail.getSize(),
                FileUtil.extName(videoThumbnail.getOriginalFilename()), null);

        //2.把视频存入fastDFS
        StorePath storePath2 = fastFileStorageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(),
                FileUtil.extName(videoFile.getOriginalFilename()), null);

        //3.封装video
        Video video = new Video();
        video.setCreated(System.currentTimeMillis());
        video.setUserId(userId);
        video.setPicUrl(fdfsWebServer.getWebServerUrl()+storePath1.getFullPath());
        video.setVideoUrl(fdfsWebServer.getWebServerUrl()+storePath2.getFullPath());

        //4.远程调用service完成保存操作
        videoService.save(video);
    }

    public ResponseEntity focusUser(Long focusUserId) {
        //1.获取登陆者id
        Long userId = UserHolder.get().getId();

        //2.封装focusUser
        FocusUser focusUser = new FocusUser();
        focusUser.setUserId(userId);
        focusUser.setFocusUserId(focusUserId);
        focusUser.setCreated(System.currentTimeMillis());

        //3.远程调用service完成保存
        focusUserService.save(focusUser);

        //4.保存关注的标识(redis) // focus_user:99_7
        stringRedisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.FOCUS_USER,userId,focusUserId),"1");
        return ResponseEntity.ok(null);
    }

    public ResponseEntity unFocusUser(Long focusUserId) {
        //1.获取登陆者id
        Long userId = UserHolder.get().getId();

        //2.远程调用service完成删除
        focusUserService.delete(userId,focusUserId);

        //3.删除关注的标识(redis)
        stringRedisTemplate.delete(StrUtil.format(ConstantUtil.FOCUS_USER,userId,focusUserId));
        return ResponseEntity.ok(null);
    }
}
